<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="缴费类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请输入缴费类型" clearable>
          <el-option label="房租" value="房租" />
          <el-option label="入驻押金" value="入驻押金" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="未审核" value="0" />
          <el-option label="审核通过" value="1" />
          <el-option label="审核不通过" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-download" size="mini" @click="exportToCSV">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="paymentList">
      <el-table-column label="缴费类型" align="center" prop="type" />
      <el-table-column label="缴费单位" align="center" prop="paymentUnit" />
      <el-table-column label="缴费金额" align="center" prop="amount" />
      <el-table-column label="缴费日期" align="center" prop="paymentDate" />
      <el-table-column label="缴费凭证" align="center" prop="paymentCertification">
        <template slot-scope="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="scope.row.paymentCertification"
            :preview-src-list="[scope.row.paymentCertification]"
            fit="cover"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">未审核</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">审核通过</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">审核不通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button v-if="scope.row.status === 0" size="mini" type="text" icon="el-icon-check" @click="handleApprove(scope.row)">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form :model="form" label-width="120px">
        <el-form-item label="缴费类型">{{ form.type }}</el-form-item>
        <el-form-item label="缴费单位">{{ form.paymentUnit }}</el-form-item>
        <el-form-item label="缴费金额">{{ form.amount }}</el-form-item>
        <el-form-item label="缴费日期">{{ form.paymentDate }}</el-form-item>
        <el-form-item label="缴费凭证">
          <el-image
            style="width: 80px; height: 80px"
            :src="form.paymentCertification"
            :preview-src-list="[form.paymentCertification]"
            fit="cover"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </el-form-item>
        <el-form-item label="状态">
          <el-tag v-if="form.status === 0" type="warning">未审核</el-tag>
          <el-tag v-else-if="form.status === 1" type="success">审核通过</el-tag>
          <el-tag v-else-if="form.status === 2" type="danger">审核不通过</el-tag>
        </el-form-item>
<!--       <el-form-item label="审核意见" v-if="form.status === 0">&ndash;&gt;-->
<!--         <el-input type="textarea" v-model="form.opinion" placeholder="请输入审核意见" />-->
<!--      </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="form.status === 0">
        <el-button type="primary" @click="handleApproveSubmit(1)">审核通过</el-button>
        <el-button type="danger" @click="handleApproveSubmit(2)">审核不通过</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPaymentlist,
  getPaymentdetatil,
  updatePayment,
  deletePayment
} from '@/api/system/payment';


export default {
  name: 'PaymentManagement',
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      paymentList: [],
      title: '',
      open: false,
      queryParams: {
        current: 1,
        pageSize: 5,
        type: null,
        status: null
      },
      form: {
        opinion: ''
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      getPaymentlist(this.queryParams)
        .then(response => {
          if (response.code === 200) {
            this.paymentList = response.data?.records || [];
            this.total = response.data?.total || 0;
          } else {
            this.$message.error('数据加载失败');
            this.paymentList = [];
            this.total = 0;
          }
        })
        .catch(error => {
          console.error(error);
          this.$message.error('网络请求异常');
          this.paymentList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    }
,
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    handleView(row) {
      getPaymentdetatil(row.id).then(response => {
        this.form = response.data;
        console.log('返回数据:', JSON.stringify(response.data, null, 2)); // 美化后的 JSON 输出

        this.open = true;
        this.title = '查看缴费记录';
      });
    },
    handleApprove(row) {
      this.handleView(row);
    },
    handleApproveSubmit(status) {
      const data = { ...this.form, status, opinion: this.form.opinion };
      updatePayment(data).then(() => {
        this.$message.success('审核成功');
        this.open = false;
        this.getList();
      });
    },
    handleDelete(row) {
      this.$confirm('是否确认删除该缴费记录？').then(() => {
        deletePayment(row.id).then(() => {
          this.$message.success('删除成功');
          this.getList();
        });
      }).catch(() => {});
    },
    cancel() {
      this.open = false;
      this.form = { opinion: '' };
    },
    // 将查询的数据导出CSV
    exportToCSV() {
      // 检查是否有数据可导出
      if (this.paymentList.length === 0) {
        this.$message.warning('没有数据可导出');
        return;
      }

      // 定义CSV表头
      const headers = [
        '缴费类型',
        '缴费单位',
        '缴费金额',
        '缴费日期',
        '状态',
        '创建时间'
      ];

      // 格式化状态文本
      const formatStatus = (status) => {
        switch(status) {
          case 0: return '未审核';
          case 1: return '审核通过';
          case 2: return '审核不通过';
          default: return '';
        }
      };

      // 准备数据行
      const rows = this.paymentList.map(item => [
        item.type || '',
        item.paymentUnit || '',
        item.amount || '',
        item.paymentDate || '',
        formatStatus(item.status),
        item.createTime || ''
      ]);

      // 处理特殊字符（如逗号、引号等）
      const escapeCsv = (field) => {
        if (typeof field === 'string') {
          // 如果包含逗号、换行符或引号，用双引号包裹并转义内部引号
          if (/[,"\n]/.test(field)) {
            return `"${field.replace(/"/g, '""')}"`;
          }
        }
        return field;
      };

      // 构建CSV内容
      const csvContent = [
        headers.map(escapeCsv).join(','),
        ...rows.map(row => row.map(escapeCsv).join(','))
      ].join('\n');

      // 创建Blob对象（添加UTF-8 BOM头解决中文乱码问题）
      const blob = new Blob(["\uFEFF" + csvContent], {
        type: 'text/csv;charset=utf-8;'
      });

      // 创建下载链接
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.href = url;

      // 设置文件名（包含当前日期）
      const now = new Date();
      const dateStr = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`;
      link.download = `缴费记录_${dateStr}.csv`;

      // 触发下载
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      this.$message.success('导出成功');
    },
  }
};

</script>

<style scoped>
.header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}
.el-card {
  margin-bottom: 20px;
}
</style>
